package com.mb.freemarker.utils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;

/**
 * @author zhanxuewei
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}
 * @date 2018/5/720:30
 */
public class CreateHtmlUtils {
    private static final Logger logger = LoggerFactory.getLogger(CreateHtmlUtils.class);
    /**
     * @return void
     * @Description
     * @Param [模板路径, 模板名称, 生成html路径, 生成html名称, 数据(要求是放在map中)]
     * @date: 2018-05-08 08:53:48
     * @author:zhanxuewei
     */
    public static void createHtml(String templatePath, String fileName, String targetPath, String targetFileName, Map map) {
        try {
            //创建一个合适的Configration对象
            Configuration configuration = new Configuration();
            configuration.setDirectoryForTemplateLoading(new File(templatePath));
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            configuration.setDefaultEncoding("UTF-8");   //这个一定要设置，不然在生成的页面中 会乱码
            //获取或创建一个模版。
            Template template = configuration.getTemplate(fileName);

            Writer writer = new OutputStreamWriter(new FileOutputStream(targetPath + targetFileName), "UTF-8");
            template.process(map, writer);

            logger.info("恭喜，生成成功~~");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
